﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Alta.Class
{


    public static class FileExtensions
    {
        public static void deleteAll(this DirectoryInfo Dir)
        {
            if (!Dir.Exists)
                return;
            foreach (FileInfo file in Dir.GetFiles())
            {
                if (IsFileLocked(file) == false)
                    file.Delete();
            }
            foreach (DirectoryInfo dir in Dir.GetDirectories())
            {
                dir.Delete(true);
            }

        }

        public static bool Copy(this FileInfo file, String toFile)
        {
            if(string.IsNullOrEmpty(toFile))
                    throw new Exception("File chuyen toi khong dc de trong");
            
            if (file.Exists)
            {
                File.Copy(file.FullName, toFile);
                return true;
            }
            return false;
        }
        public static bool IsFileLocked(this FileInfo file)
        {
            FileStream stream = null;
            try
            {
                stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            }
            catch (IOException)
            {
                return true;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
            return false;
        }
        public static string toBase64(this FileInfo file)
        {
            byte[] bytes = File.ReadAllBytes(file.FullName);
            return Convert.ToBase64String(bytes);
        }
        public static IEnumerable<FileInfo> getAllFiles(this DirectoryInfo dir, params string[] extensions)
        {
            IEnumerable<FileInfo> files = dir.EnumerateFiles();
            if (extensions == null)
                return files;
            return files.Where(f => extensions.Contains(f.Extension));
        }
    }
}
